#include "cx_string.h"
#include <windows.h>
#include <vector>

namespace CXLib {
    /// <summary>
    /// Convert wide string to UTF-8
    /// </summary>
    /// <param name="src">The wide string to convert</param>
    /// <returns>The UTF-8 encoded string</returns>
    std::string cxStrWideToUtf8(const wchar_t* src)
    {
        if (src == nullptr) return {};

        int size_needed = WideCharToMultiByte(CP_UTF8, 0, src, -1, nullptr, 0, nullptr, nullptr);
        if (size_needed <= 1) return {}; // includes null terminator, so <=1 means empty string or error

        std::string result(size_needed - 1, '\0'); // exclude null terminator

        WideCharToMultiByte(CP_UTF8, 0, src, -1, &result[0], size_needed, nullptr, nullptr);

        return result;
    }

    /// <summary>
    /// Convert UTF-8 string to wide string
    /// </summary>
    /// <param name="src">The UTF-8 encoded string to convert</param>
    /// <returns>The wide string</returns>
    std::wstring cxStrUtf8ToWide(const char* src)
    {
        if (src == nullptr) return {};

        // Get the required size for the wide string buffer (including null terminator)
        int size_needed = MultiByteToWideChar(CP_UTF8, 0, src, -1, nullptr, 0);
        if (size_needed <= 1) return {}; // error or empty string

        std::wstring result(size_needed - 1, L'\0'); // exclude null terminator

        // Convert to wide string
        MultiByteToWideChar(CP_UTF8, 0, src, -1, &result[0], size_needed);

        return result;
    }
}


